/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package com.liu.modules.business.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.liu.config.FileProperties;
import com.liu.domain.LocalStorage;
import com.liu.exception.BadRequestException;
import com.liu.modules.business.domain.EljAdvertising;
import com.liu.utils.*;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import com.liu.modules.business.repository.EljAdvertisingRepository;
import com.liu.modules.business.service.EljAdvertisingService;
import com.liu.modules.business.service.dto.EljAdvertisingDto;
import com.liu.modules.business.service.dto.EljAdvertisingQueryCriteria;
import com.liu.modules.business.service.mapstruct.EljAdvertisingMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.util.unit.DataUnit;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author Liu
* @date 2022-07-04
**/
@Service
@RequiredArgsConstructor
public class EljAdvertisingServiceImpl implements EljAdvertisingService {

    private final EljAdvertisingRepository eljAdvertisingRepository;
    private final EljAdvertisingMapper eljAdvertisingMapper;
    private final FileProperties properties;

    @Override
    public Map<String,Object> queryAll(EljAdvertisingQueryCriteria criteria, Pageable pageable){
        Page<EljAdvertising> page = eljAdvertisingRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(eljAdvertisingMapper::toDto));
    }

    @Override
    public List<EljAdvertisingDto> queryAll(EljAdvertisingQueryCriteria criteria){
        return eljAdvertisingMapper.toDto(eljAdvertisingRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public EljAdvertisingDto findById(String advertisId) {
        EljAdvertising eljAdvertising = eljAdvertisingRepository.findById(advertisId).orElseGet(EljAdvertising::new);
        ValidationUtil.isNull(eljAdvertising.getAdvertisId(),"EljAdvertising","advertisId",advertisId);
        return eljAdvertisingMapper.toDto(eljAdvertising);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public EljAdvertisingDto create(EljAdvertising resources) {
        resources.setAdvertisId(IdUtil.simpleUUID()); 
        return eljAdvertisingMapper.toDto(eljAdvertisingRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(EljAdvertising resources) {
        EljAdvertising eljAdvertising = eljAdvertisingRepository.findById(resources.getAdvertisId()).orElseGet(EljAdvertising::new);
        ValidationUtil.isNull( eljAdvertising.getAdvertisId(),"EljAdvertising","id",resources.getAdvertisId());
        eljAdvertising.copy(resources);
        eljAdvertisingRepository.save(eljAdvertising);
    }

    @Override
    public void deleteAll(String[] ids) {
        for (String advertisId : ids) {
            eljAdvertisingRepository.deleteById(advertisId);
        }
    }

    @Override
    public void download(List<EljAdvertisingDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (EljAdvertisingDto eljAdvertising : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("广告地址", eljAdvertising.getAdvertisUrl());
            map.put("广告图片地址", eljAdvertising.getAdvertisImgUrl());
            map.put("广告公司", eljAdvertising.getAdvertisCompany());
            map.put("广告图片大小",eljAdvertising.getAdvertisImgSize());
            map.put("广告图片类型",eljAdvertising.getAdvertisImgType());
            map.put("状态", eljAdvertising.getAdvertisStatus());
            map.put("发布时间", eljAdvertising.getAdvertisStartTime());
            map.put("结束时间", eljAdvertising.getAdvertisEndTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public EljAdvertising upload(String name, String advertisCompany,String advertisUrl,String advertisEndTime,MultipartFile multipartFile){
        FileUtil.checkSize(properties.getMaxSize(), multipartFile.getSize());
        String suffix = FileUtil.getExtensionName(multipartFile.getOriginalFilename());
        String type = FileUtil.getFileType(suffix);
        File file = FileUtil.upload(multipartFile, properties.getPath().getPath() + type +  File.separator);
        if(ObjectUtil.isNull(file)){
            throw new BadRequestException("上传失败");
        }
        try {
            name = StringUtils.isBlank(name) ? FileUtil.getFileNameNoEx(multipartFile.getOriginalFilename()) : name;
            EljAdvertising eljAdvertising = new EljAdvertising();
            eljAdvertising.setAdvertisId(IdUtil.simpleUUID());
            eljAdvertising.setAdvertisCompany(advertisCompany);
            eljAdvertising.setAdvertisUrl(advertisUrl);
            eljAdvertising.setAdvertisImgUrl(file.getPath());
            eljAdvertising.setAdvertisImgSize(FileUtil.getSize(multipartFile.getSize()));
            eljAdvertising.setAdvertisImgType(type);
            eljAdvertising.setAdvertisName(name);
            eljAdvertising.setAdvertisStatus("1");
            eljAdvertising.setAdvertisImgSuffix(suffix);
            eljAdvertising.setAdvertisImgRealName(file.getName());
            eljAdvertising.setAdvertisStartTime(DateUtil.localDateTimeFormat(DateUtil.toLocalDateTime(new Date()), "yyyy-MM-dd"));
            eljAdvertising.setAdvertisEndTime(advertisEndTime);
            return eljAdvertisingRepository.save(eljAdvertising);
        }catch (Exception e){
            FileUtil.del(file);
            throw e;
        }
    }
}